import { FC, useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import * as _ from 'lodash';
import { AtButton, AtModal, AtModalContent, AtTag } from 'taro-ui';
import styles from './index.less';

/**
 * @props:
 *  title: 显示的标题
 *  visible: 是否显示
 *  tagListObj: 对象, 形如:
 *   {
 *     'carType': {
 *         tagList: ['卡车', '汽车'],
 *         isMulti?: true // 默认单选，可不传
 *      }
 *     'carLength': {
 *        tagList: ['1.8', '2.3'],
 *        isMulti?: false // 默认单选，可不传
 *      }
 *   }
 *  每一项都会渲染出一个tag选择区域，其中key为title, value为选择项以及该选择项是否多选
 *  cancleCallback: 取消的回调
 *  confirmCallback: 确认的回调
 */
const TagListPick: FC<tagListPickPropsType> = (props: tagListPickPropsType) => {
  const { visible, title, tagListObj, cancleCallback, confirmCallback } = props;
  const [isVisible, setIsVisible] = useState<boolean>(visible);
  const [tagListSource, setTagListSource] = useState<handledTagListObjType>({});

  useEffect(() => {
    setIsVisible(visible);
  }, [visible]);

  useEffect(() => {
    const tagListObjDeepClone = _.cloneDeep(tagListObj);

    Object.keys(tagListObjDeepClone).forEach((key) => {
      const newTagList = tagListObjDeepClone[key]['tagList'].map((tagItem) => {
        return {
          tag: tagItem,
          isChecked: false,
        };
      });
      tagListObjDeepClone[key]['tagList'] = newTagList;
    });
    setTagListSource(tagListObjDeepClone);
  }, []);

  // 点击tag
  const handleTagCheck = (itemTitle: string, isMulti: boolean, idx: number) => {
    const tagListSourceDeepClone = _.cloneDeep(tagListSource);

    /** 更改当前tag的选中状态 */
    const tagCheckedCurr =
      !tagListSourceDeepClone[itemTitle].tagList[idx].isChecked;
    const newTagListArr = tagListSourceDeepClone[itemTitle].tagList;
    newTagListArr[idx].isChecked = tagCheckedCurr;

    const newTagListSource = {
      ...tagListSourceDeepClone,
      [itemTitle]: {
        ...tagListSourceDeepClone[itemTitle],
        tagList: newTagListArr,
      },
    };
    setTagListSource(newTagListSource);

    // 处理单选的情况
    if (!isMulti) {
      if (tagCheckedCurr) {
        // 选中一项
        tagListSourceDeepClone[itemTitle].tagList.forEach((item, index) => {
          item.isChecked = false;
          if (index === idx) {
            item.isChecked = true;
          }
        });
      } else {
        // 取消一项
        tagListSourceDeepClone[itemTitle].tagList[idx].isChecked = false;
      }
      setTagListSource(tagListSourceDeepClone);
    }
  };

  // 确定
  const handleConfirm = () => {
    const res: arrObject = {};
    Object.keys(tagListSource).forEach((itemTitle) => {
      res[itemTitle] = [];

      tagListSource[itemTitle].tagList.forEach((tagObj) => {
        if (tagObj.isChecked) {
          res[itemTitle].push(tagObj.tag);
        }
      });
    });

    confirmCallback(res);
  };

  return (
    <AtModal
      className={styles.tag_list_pick_modal}
      isOpened={isVisible}
      closeOnClickOverlay={false}
    >
      <AtModalContent>
        <View className="title_bar">
          <AtButton className="cancle_btn" onClick={cancleCallback}>
            取消
          </AtButton>
          <Text>{title}</Text>
          <AtButton className="confirm_btn" onClick={handleConfirm}>
            确认
          </AtButton>
        </View>
        <View className="list">
          {Object.keys(tagListSource).map((itemTitle, idx) => {
            return (
              <View key={`${itemTitle}-${idx}`} className="list_item">
                <View className="item_title">{itemTitle}</View>
                <View className="item_tags">
                  {tagListSource[itemTitle]['tagList'].map((itemObj, index) => {
                    const { isMulti = false } = tagListSource[itemTitle];
                    const { tag, isChecked } = itemObj;
                    return (
                      <AtTag
                        key={`${tag}-${index}`}
                        name={tag}
                        active={isChecked}
                        onClick={() =>
                          handleTagCheck(itemTitle, isMulti, index)
                        }
                      >
                        {tag}
                      </AtTag>
                    );
                  })}
                </View>
              </View>
            );
          })}
        </View>
      </AtModalContent>
    </AtModal>
  );
};

export default TagListPick;
